import React, { useState } from 'react';
import { Form, Input, Button, Card, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { login } from 'services/auth';
import './index.css';

const Login = () => {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values) => {
    try {
      setLoading(true);
      const response = await login(values.username, values.password);
      console.log(response);
      if (response.code === 200) {
        // 登录成功
        localStorage.setItem('token', response.token);
        localStorage.setItem('userInfo', JSON.stringify(response.userinfo));
        localStorage.setItem('isLoggedIn', 'true');
        
        message.success({
          content: response.message,
          duration: 1,
          onClose: () => navigate('/zlvehicle/insuranceManage')
        });
      } else {
        // 登录失败
        message.error({ 
          content: response.message,
          duration: 2
        });
      }
    } catch (error) {
      message.error({ 
        content: '后台服务未启动',
        duration: 2
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-container">
      <div className="login-content">
        <Card bordered={false} className="login-card">
          <div className="login-header">
            <h2>车辆管理系统</h2>
            <p>欢迎登录</p>
          </div>
          <Form
            name="login"
            onFinish={onFinish}
            autoComplete="off"
            size="large"
          >
            <Form.Item
              name="username"
              rules={[
                {
                  required: true,
                  message: '请输入用户名',
                },
              ]}
            >
              <Input 
                prefix={<UserOutlined />} 
                placeholder="请输入用户名" 
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  message: '请输入密码',
                },
              ]}
            >
              <Input.Password 
                prefix={<LockOutlined />} 
                placeholder="请输入密码" 
              />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                block
                loading={loading}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    </div>
  );
};

export default Login; 